<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<!-- 关联信息区域 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>关联信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_JobAssignmentId_FormItem" prop="Entity.JobAssignmentId">
								<template #label>
									<WtmLabelTooltip label="分岗申请单号" tooltip="关联的分岗申请单" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.JobAssignmentId" clearable class="width100" :disabled="isEntityIdFromExternal">
									<el-option
										v-for="item in stateData.AllSysHrJobAssignmentRequestBills"
										:key="item.Value"
										:value="item.Value"
										:label="item.Text"
									></el-option
								></el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<!-- 人员信息区域 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>人员信息</span>
					</div>
					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_PersonId_FormItem"
								prop="Entity.PersonId"
								:rules="[{ required: true, message: '员工为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="员工" tooltip="关联的员工实体" />
								</template>
								<WtmPersonSelector v-model="stateData.vmModel.Entity.PersonId" :prefillPerson="currentPerson" @change="handlePersonChange" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
								<template #label>
									<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
								</template>
								<el-input
									v-model="stateData.vmModel.Entity.StaffNo"
									clearable
									class="width100"
									:disabled="true"
									placeholder="选择员工后自动填充"
								></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
								<template #label>
									<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
								</template>
								<el-input
									v-model="stateData.vmModel.Entity.Name"
									clearable
									class="width100"
									:disabled="true"
									placeholder="选择员工后自动填充"
								></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_EntryRemark_FormItem" prop="Entity.EntryRemark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="分岗备注信息" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.EntryRemark" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<!-- 工作信息区域 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>工作信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmOrgSelector v-model="stateData.vmModel.Entity.OrgId" label="公司" :disabled="isOrgIdFromExternal" :rules="[{ required: true, message: '公司为必填项', trigger: 'blur' }]" />
						</el-col>
					</el-row>
					<wtm-dept-selector
						v-model="stateData.vmModel.Entity.GroupId"
						label="所属部门"
						:show-position="true"
						v-model:position-id="stateData.vmModel.Entity.JobPositionId"
						position-label="工作岗位"
						:use-row="true"
						:dept-col="12"
						:position-col="12"
						:org-id="stateData.vmModel.Entity.OrgId"
						:rules="[{ required: true, message: '工作岗位为必填项', trigger: 'blur' }]"
						:position-rules="[{ required: true, message: '工作岗位为必填项', trigger: 'blur' }]"
					/>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.edit;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, nextTick, type ComponentInternalInstance } from 'vue';
import { SysHrJobAssignmentRequestBillEntryApi as api } from '/@/views/hr/syshrjobassignmentrequestbillentry/api';
import other from '/@/utils/other';
import { ISysHrJobAssignmentRequestBillEntryVm } from '/@/views/hr/syshrjobassignmentrequestbillentry/api/interface';
import { IViewModel } from '/@/types/common';
import type { ISysPersonView } from '/@/views/person/sysperson/api/interface';

// 常量定义
const BUTTON_TEXTS = {
	SUBMIT: '提交',
	SAVE: '保存',
	CLOSE: '关闭',
} as const;

const API_ENDPOINTS = {
	BILLS: '/api/SysHrJobAssignmentRequestBillEntry/GetSysHrJobAssignmentRequestBills',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const isEntityIdFromExternal = ref(false);
const isOrgIdFromExternal = ref(false);

// 初始化表单数据
const stateData = reactive<IViewModel<ISysHrJobAssignmentRequestBillEntryVm>>({
	vmModel: {
		Entity: {
			ID: null,
			PersonId: null,
			StaffNo: null,
			Name: null,
			JobPositionId: null,
			GroupId: null,
			OrgId: null,
			EntryRemark: null,
			JobAssignmentId: null,
		},
	},
	AllSysHrJobAssignmentRequestBills: [],
	AllSysJobPositions: [],
	AllSysGroups: [],
	AllSysOrgs: [],
});

// 当前选择的人员信息（用于回显）
const currentPerson = ref<ISysPersonView | null>(null);

// 统一的成功处理函数
const handleSuccess = () => {
	ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '操作成功');
	emit('refresh');
	loading.value = false; // 重置loading状态
	closeDialog();
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的表单提交函数
const submitForm = (apiCall: () => Promise<any>) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			apiCall().then(handleSuccess).catch(handleError);
		}
	});
};

// 人员选择变化处理
const handlePersonChange = (value: string | null, person: ISysPersonView | null) => {
	if (person) {
		// 自动填充员工信息并禁用字段
		stateData.vmModel.Entity.StaffNo = person.StaffNo;
		stateData.vmModel.Entity.Name = person.Name;
		currentPerson.value = person;
	} else {
		// 清空员工信息，字段将变为可编辑状态
		stateData.vmModel.Entity.StaffNo = null;
		stateData.vmModel.Entity.Name = null;
		currentPerson.value = null;
	}
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	submitForm(() => api().edit(stateData.vmModel));
};

// 提交单据
const onSubmit = () => {
	onSave();
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	const routeId = window.location.search.match(/[?&]id=([^&]*)/)?.[1];

	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	} else if (routeId) {
		stateData.vmModel.Entity.ID = routeId as any;
	}

	// 如果从主单据传入了entityId，设置到JobAssignmentId中并标记为外部传入
	if (wtmdata?.entityId) {
		stateData.vmModel.Entity.JobAssignmentId = wtmdata.entityId;
		isEntityIdFromExternal.value = true;
	} else if (wtmdata?.Entity?.JobAssignmentId) {
		// 兼容直接在Entity中传递JobAssignmentId的情况
		stateData.vmModel.Entity.JobAssignmentId = wtmdata.Entity.JobAssignmentId;
		isEntityIdFromExternal.value = true;
	}

	// 如果从主单据传入了部门ID，设置到GroupId中
	if (wtmdata?.groupId) {
		stateData.vmModel.Entity.GroupId = wtmdata.groupId;
	}

	// 如果从主单据传入了公司ID，设置到OrgId中并标记为外部传入
	if (wtmdata?.orgId) {
		stateData.vmModel.Entity.OrgId = wtmdata.orgId;
		isOrgIdFromExternal.value = true;
	}
};

// 加载页面数据
const loadPageData = async () => {
	const [bills, entityData] = await Promise.allSettled([
		other.getSelectList(API_ENDPOINTS.BILLS, [], false),

		api().get(stateData.vmModel.Entity.ID ?? ''),
	]);

	if (bills.status === 'fulfilled') stateData.AllSysHrJobAssignmentRequestBills = bills.value;

	if (entityData.status === 'fulfilled') {
		other.setValue(stateData.vmModel, entityData.value);
		// 设置当前人员信息用于回显
		if (stateData.vmModel.Entity.PersonId && stateData.vmModel.Entity.Name) {
			currentPerson.value = {
				ID: stateData.vmModel.Entity.PersonId,
				Name: stateData.vmModel.Entity.Name,
				StaffNo: stateData.vmModel.Entity.StaffNo,
			} as ISysPersonView;
		}
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	try {
		// 首先初始化页面数据（获取ID）
		initializePageData();

		// 然后加载选择列表数据
		await loadPageData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 监听部门变化，联动岗位（由wtm-dept-selector组件处理）

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onSubmit,
			visible: true,
		},
		{
			text: BUTTON_TEXTS.SAVE,
			type: 'info',
			onClick: onSave,
			visible: true,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
